/*
 * 弹框用户选择器
 *
 * @author 曾文
 * @since 2018/10/18
 */
import React from 'react';
import {
    Modal, Row, Col, Form, TreeSelect, Select, Table, Input, Button, Icon, Checkbox, Popconfirm, message, Radio
} from 'antd';
import { Link } from "dva/router";
import { request } from '../../config/request'
import $ from 'jquery';
import { cloneDeep, get } from 'lodash'
import AdvanceSearch from '../CollapsiblePanels/AdvanceSearch'
import { QueryCondition } from '../Grid/Grid'
import config from '../../config/config'
import cx from 'classnames'

const { Component } = React
const FormItem = Form.Item
const { Option, OptGroup } = Select
const TreeNode = TreeSelect.TreeNode
const formItemLayout1 = {
    labelCol: { span: 9 }, wrapperCol: { span: 15 }
};

import Keypress  from 'widget/Keypress'
/*
*
* 产品选择组件
*
*/
export default class extends Component {
    // 构造函数
    constructor(props, context) {
        super(props, context);
        this.state = {

            dataSource: [],//列表数据
            detailData: {},//搜索条件
            //组件宽度
            modalWidth: 1000,
            //右侧选择框的高度
            maxHeight: 403,
            //表格数据加载标志
            loadingFlag: true,
            pageNo: 1,//当前页
            pageSize: 10,//单页条数
            tableData: [],

            //关闭按钮  必填
            closeCbk: () => {
                this.props.onCancel();
            },
            // 确认回调
            confirmCbk: (item) => {
                this.props.onOk(item)
            }
        }

    }


    //Modal初始化
    componentWillMount() {
        this.setModalWidth()
        // this.getUserList()
        // 还需新增state初始化
    }

    //准备：即将被重新渲染，状态未变化
    componentWillUpdate(nextProps, nextState) {
        let self = this;
        //浏览器大小改变的时候
        window.onresize = function () {
            if (self.state.visible) {
                self.setModalWidth()
            }
        };
    }

    //完成：正在被重新渲染，状态已变化
    componentDidUpdate(prevProps, prevState) {
        // this.getTableHeight()
    }

    // 已加载组件，收到新属性时调用
    componentWillReceiveProps(nextProps) {
        // this.state.propsParameter.selArea = nextProps.selArea;
        // this.setState({});
        this.state.visible = nextProps.visible;
        if (this.state.visible == true) {
            if (nextProps.isSave) {
                let selectedProduct = cloneDeep(nextProps.onItem).map(item => {
                    item.key = item[nextProps.idKey]
                    item.itemName = item.name
                    return item
                })
                this.setState({
                    selectedProduct,
                    itemIds: nextProps.itemIds
                })
            }
            this.setState({
                queryList: nextProps.queryList
            }, () => {
                this.getUserList();
            });
        }
    }

    // 插入真实 DOM
    componentDidMount() {

    }


    //获取产品列表
    async getUserList() {
        let detailData = this.state.detailData
        let that = this;
        this.setState({
            loadingFlag: true,
        })
        let { pageNo, pageSize, search, queryList } = cloneDeep(that.state)
        //组装接口入参


        let data = await request({
            url: "/admin/propertyConsultant/queryFrom4A",
            method: 'POST',
            headers: {
                "Content-type": "application/json"
            },
            data: {
                pageNo,
                pageSize,
                ...detailData,
            }
        });

        if (data.success) {
            data.data && data.data.map((x, i) => {
                x["checked"] = false
                x["key"] = i + 1

            })

            this.setState({
                dataSource: data.data,
                tableData: data,
                total: data.total,
                loadingFlag: false,
            })
        }
    }

    // 设置Modal宽度
    setModalWidth() {
        let windowWidth = document.body.clientWidth
        let modalWidth = windowWidth * 0.8 > 1200 ? 1200 : windowWidth * 0.8
        this.setState({ modalWidth })
    }

    //分页发生时所调用的方法
    pageChangeHandler(page, size) {
        this.setState({
            pageNo: page,
            pageSize: size
        }, this.getUserList)
    }

    // 设置分页
    setPagination() {
        return {
            current: parseInt(this.state.pageNo),//当前页
            pageSize: this.state.pageSize,//单页条数
            total: this.state.total,//总条数
            simple: true,
            showTotal: e => `共 ${this.state.total} 条`,
            showSizeChanger: true,
            showQuickJumper: true,
            onShowSizeChange: (page, size) => {
                this.pageChangeHandler(page, size)
            },
            onChange: (page, size) => {
                this.pageChangeHandler(page, size)
            }
        }
    }



    //弹窗的确定按钮
    handleConfirm() {
        let dataSource = this.state.dataSource
        let selectObj = ''
        dataSource.map((x) => {
            if (x.checked) {
                selectObj = x
            }
        })
        this.state.confirmCbk(selectObj)
        this.state.closeCbk()
    }

    //弹窗的取消按钮
    handleCancel() {
        this.state.closeCbk()
    }

    //弹窗的查询按钮
    handleSearch() {
        this.setState({
            pageNo: 1,
            pageSize: 10
        }, () => {
            this.getUserList()
        })
    }



    //数据更新
    inputChange(name, value) {
        let detailData = this.state.detailData
        let obj = { [name]: value }
        detailData = Object.assign(detailData, obj)
        this.setState({
            detailData
        })
    }

    render() {
        let dataSource = this.state.dataSource
        let detailData = this.state.detailData
        console.log("fff===", dataSource)

        const columns = [
            {
                title: '', dataIndex: 'radio', key: 'radio', width: 28,
                render: (text, record, index) => {
                    return (<div>
                        <Radio checked={record.checked} onChange={(e) => {
                            dataSource.map((x, i) => {
                                if (x.key == record.key) {
                                    x.checked = true
                                } else {
                                    x.checked = false
                                }
                            })
                            this.setState({
                                dataSource
                            })
                        }
                        } > </Radio>
                    </div>)
                }
            },
            { title: '用户账号', dataIndex: 'uid', key: 'uid',},
            { title: '姓名', dataIndex: 'name', key: 'name', },
            {
                title: '性别', dataIndex: 'sex', key: 'sex',
                render: (text, x, index) => {
                    let txt = ""
                    if (x.sex == 0) {
                        txt = "女"
                    } else if(x.sex == 1){
                        txt = "男"
                    }
                    return <div>
                        {txt}
                    </div>
                }
            },
            { title: '手机号', dataIndex: 'mobile', key: 'mobile',},
            // {
            //     title: '身份证号码', dataIndex: 'idCardNo', key: 'idCardNo', width: 130,
            // },

        ]

        let self = this
        return (
            <div>
              {/*监控键盘事件，自动刷新数据*/}
              <Keypress keyCode={13} cbk={()=>{
                this.handleSearch()
              }} />
                
                <Modal
                    title={this.props.title || '选择'}
                    visible={this.props.visible}
                    onOk={this.handleConfirm.bind(this)}
                    onCancel={this.handleCancel.bind(this)}
                    width={this.state.modalWidth}
                >
                    {
                        <div>
                            <Row>
                                <Col span={6}>
                                    <FormItem {...formItemLayout1} label="姓名" hasFeedback>
                                        <Input value={detailData.name} onChange={e => this.inputChange('name', e.target.value)} />
                                    </FormItem>
                                </Col>
                                <Col span={6}>

                                    <FormItem {...formItemLayout1} label="用户账号" hasFeedback>
                                        <Input value={detailData.uid} onChange={e => this.inputChange('uid', e.target.value)} />
                                    </FormItem>
                                </Col>

                                <Col span={6}>
                                    <FormItem {...formItemLayout1} label="手机号" hasFeedback>
                                        <Input value={detailData.mobile} onChange={e => this.inputChange('mobile', e.target.value)} />
                                    </FormItem>
                                </Col>

                                <Col span={6}>
                                    <Button type='primary' style={{ marginTop: 4, marginLeft: 32 }} onClick={() => { this.handleSearch() }}>搜索</Button>
                                </Col>

                            </Row>
                        </div>
                    }

                    <div>
                        <Table columns={columns}
                            pagination={this.setPagination()}
                            dataSource={dataSource}
                            onRow={(record, index) =>{onClick:()=> {
                                dataSource.map((x, i) => {
                                    if (i == index) {
                                        x.checked = true
                                    } else {
                                        x.checked = false
                                    }
                                })
                                this.setState({ dataSource })
                            }}}
                        />
                    </div>
                </Modal>
            </div>
        )
    }

}
